package br.com.rafsoft.mapaentrega.client;

import br.com.rafsoft.mapaentrega.shared.MapaEntregaRequestFactory;
import br.com.rafsoft.mapaentrega.shared.UserProxy;
import br.com.rafsoft.mapaentrega.shared.UserRequest;

import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.InputElement;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Widget;
import com.google.web.bindery.event.shared.EventBus;
import com.google.web.bindery.event.shared.SimpleEventBus;
import com.google.web.bindery.requestfactory.shared.Receiver;

public class UserWidget extends Composite {

	private static UserWidgetUiBinder uiBinder = GWT
			.create(UserWidgetUiBinder.class);
	private final MapaEntregaRequestFactory requestFactory = GWT
			.create(MapaEntregaRequestFactory.class);
	private final EventBus eventBus = new SimpleEventBus();

	interface UserWidgetUiBinder extends UiBinder<Widget, UserWidget> {
	}

	@UiField
	Button createUserButton;

	@UiField
	InputElement userNameArea;

	@UiField
	InputElement nameArea;

	@UiField
	InputElement passwordArea;

	public UserWidget() {
		initWidget(uiBinder.createAndBindUi(this));
		
		requestFactory.initialize(eventBus);
	}

	@UiHandler("createUserButton")
	void onCreateUserButtonClick(ClickEvent event) {
		UserRequest request = requestFactory.userRequest();
		UserProxy user = request.create(UserProxy.class);

		user.setUserName(userNameArea.getValue());
		user.setName(nameArea.getValue());
		user.setPassword(passwordArea.getValue());

		request.updateUser(user).fire(new Receiver<UserProxy>() {

			@Override
			public void onSuccess(UserProxy user) {
				Window.alert("CREATE SUCCESS: " + user.getId());
			}
		});

	}
}
